package com.dofuntech.dataplatform.protocal;





import org.apache.mina.core.buffer.IoBuffer;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.List;

/**
 * Created by Administrator on 2019/7/9 0009.
 */

public class BdPositionBody extends PositionBody {

    protected  short mCoord  ;
    protected  String psd   ;
    protected  String plate ;
    private static  CharsetEncoder mCharsetEncoder = null ;
    public BdPositionBody(){
        mCoord = Position.COORD_BD ;
    }


    protected CharsetEncoder getCharsetEncoder (){
        if(mCharsetEncoder == null)
            mCharsetEncoder =  Charset.forName("GBK").newEncoder();
        return  mCharsetEncoder;
    }



    public BdPositionBody(String[] AKEY, List<Position> positions) {
        super(AKEY,positions);
        mCoord = Position.COORD_BD ;
        if(AKEY.length > 2){
            psd = AKEY[1];
            plate = AKEY[2];
        }
    }

    @Override
    public Command command() {
        return Command.BDPOSITION;
    }


    @Override
    public void writeTo(IoBuffer encoder) throws IOException {
        int start ;
        start = encoder.position();
        byte[] bytes = stringHex2Bytes(this.AKEY);
        encoder.put(bytes);  //ak[0] user&time
        //密码
        encoder.putString (psd, getCharsetEncoder());
        encoder.put((byte) 0);
        //车牌
        encoder.putString (plate, getCharsetEncoder());
        encoder.put((byte) 0);


        encoder.putUnsigned( size); //点数
        encoder.putUnsigned(mCoord);

        for(int i = 0 ; i < positions.size() ;i ++) {
            Position pos = positions.get(i);
            encoder.putInt(pos.getLat());
            encoder.putInt(pos.getLng());
            encoder.putInt(pos.getHeight());
            encoder.putUnsignedInt(pos.getSecond());

            encoder.putUnsignedShort(pos.getSpeed());
            encoder.putUnsignedShort(pos.getContinual());
            encoder.putUnsignedShort(pos.getBearing());
            encoder.putUnsigned(pos.getLocType());
            encoder.putUnsigned(i);//保留
        }

        contentSize = encoder.position() - start;
    }
}
